//
//  UserDefaults+ZLExtensions.swift
//  ZLKit_Swift
//
//  Created by itzhaolei on 2022/1/18.
//


public extension UserDefaults {
    
    static private var _user: [String:String]? = nil
    static var user: [String:String]? {
        get{
            guard let safeUser = _user else {
                _user = getUserPrivateData()
                return _user
            }
            return safeUser
        }
    }
    
    class UserDefaultsKey {
        class ZLKit_Swift_PrivateData: NSObject { }
        static var userPrivateData: String = NSStringFromClass(ZLKit_Swift_PrivateData.classForCoder())
    }
    
    /// 更新一个些键值对到用户隐私数据里
    ///
    /// 相同键会被覆盖，不同键将会新增
    ///
    static func updateValues(values: [String:String]) {
        var userPrivateData = getUserPrivateData() ?? [:]
        for (key, value) in values {
            userPrivateData[key] = value
        }
        save(value: userPrivateData)
    }
    
    /// 获取用户私有数据
    static func getUserPrivateData() -> [String:String]? {
        guard let jsonStr_base64 = Self.standard.object(forKey: UserDefaultsKey.userPrivateData) as? String else { return nil }
        return jsonStr_base64.base64Decoding.toContainers() as? [String:String]
    }
    
    /// 清理用户私有数据
    static func clearUserPrivateData() {
        save()
    }
    
    /// 存储数据
    static private func save(value: Any? = nil) {
        var data = value
        if let safeData = data as? [String:String] {
            data = safeData.toString()?.base64Encoding
        }
        Self.standard.setValue(data, forKey: UserDefaultsKey.userPrivateData)
        Self.standard.synchronize()
        _user = value as? [String:String] ?? nil
        postNotification(.userPrivateData)
    }
    
}
